#include "media_dispatcher.h"

using namespace VLRTSP;



/**
 * @Author: CimZzz
 * @Date: 2022-01-13 19:32:31
 * 
 * 构造函数
 * @param id 媒体分发器 Id
 * @param rtpSendPoint RTP 发送端口 / Channel
 * @param rtcpSendPoint RTCP 发送端口 / Channel
 * @param mediaSource 媒体资源
 */
MediaDispatcher::MediaDispatcher(uint32_t id, uint16_t rtpSendPoint, uint16_t rtcpSendPoint, std::shared_ptr<MediaSource> mediaSource): mediaSource(mediaSource),
	sendThread([this](std::shared_ptr<RTPFrame> data){
	this->onRecvSendBuffer(data);
}) {
	this->id = id;
	this->rtpSendPoint = rtpSendPoint;
	this->rtcpSendPoint = rtcpSendPoint;
	this->isPlaying = false;
	this->callbackCode = 0;
}

/**
 * @Author: CimZzz
 * @Date: 2022-01-13 19:32:40
 * 
 * 析构函数
 */
MediaDispatcher::~MediaDispatcher() {
	this->isPlaying = false;
	if(callbackCode != 0) {
		this->mediaSource.get()->removeFrameSendCallback(callbackCode);
	}
	this->callbackCode = 0;
}


/**
 * @Author: CimZzz
 * @Date: 2022-01-13 19:33:51
 * 
 * 分发数据帧
 * @param rtpFram RTP 数据帧
 */
void MediaDispatcher::dispatch(std::shared_ptr<RTPFrame> rtpFrame) {
	this->sendThread.send(rtpFrame);
}


/**
 * @Author: CimZzz
 * @Date: 2022-01-14 11:48:47
 * 
 * 开始分发数据
 */
void MediaDispatcher::start() {
	sendThread.start();
	this->isPlaying = true;
	this->callbackCode = mediaSource.get()->addFrameSendCallback([this](std::shared_ptr<RTPFrame> data){
		this->dispatch(data);
	});
}


/**
 * @Author: CimZzz
 * @Date: 2022-01-14 17:11:23
 * 
 * 获取媒体数据分发器 Id
 */
uint32_t MediaDispatcher::getDispatcherId() {
	return this->id;
}


/**
 * @Author: CimZzz
 * @Date: 2022-01-14 20:03:36
 * 
 * 获取 RTP 端口 / Channel
 * @return RTP 端口 / Channel
 */
uint16_t MediaDispatcher::getRTPStartPoint() {
	return this->rtpSendPoint;
}

/**
 * @Author: CimZzz
 * @Date: 2022-01-14 20:03:57
 * 
 * 获取 RTCP 端口 / Channel
 * @return RTCP 端口 / Channel
 */
uint16_t MediaDispatcher::getRTCPStartPoint() {
	return this->rtcpSendPoint;
}

